package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.ChangeCourse;
import com.example.demo.entity.Course;
import com.example.demo.entity.Response;
import com.example.demo.entity.User;
import com.example.demo.security.jwt.JwtTokenUtil;
import com.example.demo.service.JwtUserDetailService;
import com.example.demo.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Objects;


@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUserDetailService jwtUserDetailService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @GetMapping("/login")
    /**
     * 成功登陆，
     * 返回{
     *     "code": 200,
     *     "msg": "completed",
     *     "data": {
     *         "role":
     *         "mail":
     *         "identityid":
     *         "firstlogin":
     *         "name":
     *         "phonenumber":
     *         "id":
     *         "message":
     *         "authorities":
     *         "token":
     *     }
     * 登陆失败，
     * 返回{
     *     "code": 999,
     *     "msg": "用户名或密码错误",
     *     "data": null
     * }
     */
    public Response login(String ID, String password){
        HashMap validity = userService.login(ID,password);
        System.out.println("id: "+validity.get("id"));
        String errMsg = null;
        if(validity.get("message")=="forbidden")
            return Response.ok(999,"无权限登录");

        if (validity.get("id")!=null&&Objects.equals(validity.get("id"),ID)){
            System.out.println("进入token生成");

            User user = userService.findUserById(ID);
            System.out.println("user_id:  "+user.getID());

            String token = jwtTokenUtil.generateToken(user, validity.get("authorities").toString());
            validity.put("token",token);
            userService.saveToken(ID,token);
            return Response.ok(validity);
        }
        else{
            if(userService.findUserById(ID)==null){
                errMsg="用户ID不存在";
            }
            else{
                errMsg="用户名或密码错误";
            }
        }
        return Response.ok(999,errMsg);

    }

    @PostMapping("/pwd")
    public Response changePwd(@RequestHeader("Authorization") String token,
                              @RequestParam String ID, @RequestParam String oldPwd,@RequestParam String newPwd) {
            System.out.println("进入修改密码");
            System.out.println("token:"+token);
        if(!userService.validateToken(ID, token))
            return Response.ok(999,"用户ID与令牌不一致");
        return Response.ok(userService.changePwd(ID, oldPwd,newPwd));
    }

    @PostMapping("/inf")
    public Response changInf(@RequestHeader("Authorization") String token,
                             @RequestParam String ID, @RequestParam String newmail,
                             @RequestParam String newphonenumber){
        System.out.println("进入修改个人信息");
        System.out.println("token"+token);
        if(!userService.validateToken(ID, token))
            return Response.ok(999,"用户ID与令牌不一致");
        return Response.ok(200,"请求完成",userService.changeInf(ID, newmail, newphonenumber));
    }

    @GetMapping("getInf")
    public Response getInf(@RequestHeader("Authorization") String token){
        String ID = jwtTokenUtil.getUseridFromToken(token);
        if(!userService.validateToken(ID, token))
            return Response.ok(999,"用户ID与令牌不一致");
        HashMap result = userService.getInf(ID);
        if(result.get("error")!=null)
            return Response.ok(500,"请求失败",result);
        else
            return Response.ok(200,"请求成功",result);
    }

    //教师申请新增课程
    @PostMapping("/addCourse")
    public Response addCourse(@RequestHeader("Authorization") String token,
                              @RequestBody JSONObject jsonObject){
        Course course = JSONObject.parseObject(jsonObject.toJSONString(), Course.class);
        String id=jwtTokenUtil.getUseridFromToken(token);
        User user = userService.findUserById(id);
        course.setCteacher(user.getName());
        System.out.println(course);
        if(jwtTokenUtil.validateToken(token,user)&& Objects.equals(user.getRole(), "teacher")){
            HashMap result = userService.addCourse(course,user);
            if(result.get("result")=="success")
                return Response.ok(200,"申请成功");
            return Response.ok(500,"申请失败",result);
        }
        else{
            return Response.ok(999,"身份验证失败： "+user.getRole());
        }
    }

    //教师申请修改课程
    @PostMapping("/changeCourse")
    public Response changeCourse(@RequestHeader("Authorization") String token,
                                 @RequestBody JSONObject jsonObject){
        String id=jwtTokenUtil.getUseridFromToken(token);
        User user = userService.findUserById(id);
        System.out.println(user.getName());
        ChangeCourse changeCourse = JSONObject.parseObject(jsonObject.toJSONString(),ChangeCourse.class);
        System.out.println(changeCourse);
        if(jwtTokenUtil.validateToken(token,user)&& Objects.equals(user.getRole(), "teacher")){
            HashMap<String,String> result = userService.changeCourse(changeCourse,user);
            System.out.println(result.size());
            //System.out.println(result.get(result.size()));
            if(Objects.equals(result.get("result"), "success"))
                return Response.ok(200,"申请成功");
            return Response.ok(500,"申请失败",result);
        }
        else{
            return Response.ok(999,"身份验证失败： "+user.getRole());
        }

    }

    //教师申请删除课程
    @PostMapping("/deleteCourse")
    public Response deleteCourse(@RequestHeader("Authorization") String token, @RequestParam Integer cid){
        if(userService.deleteCourse(cid)==200){
            return Response.ok(200,"申请成功");
        }
        else{
            return Response.ok(500,"申请失败");
        }
    }

    //用户查看自己的/可选的课程
    @GetMapping("/getMyOrMajorCourses")
    public Response getUserCourses(@RequestHeader("Authorization") String token){
        String id = jwtTokenUtil.getUseridFromToken(token);
        HashMap resMap = userService.getMyOrMajorCourses(id);
        if(resMap.get("error")!=null)
            return Response.ok(400,"选课功能尚未开启");
        return Response.ok(200,"查询结束",userService.getMyOrMajorCourses(id));
    }

    //教师查看所有的教室
    @GetMapping("/getRoom")
    public Response getRooms(@RequestHeader("Authorization") String token){
        String id = jwtTokenUtil.getUseridFromToken(token);
        HashMap result = userService.UserGetRooms(id);
        if(result.get("error")!=null){
            return Response.ok(500,"该功能不对该用户开放");
        }
        else{
            return Response.ok(200,"查询结束",result);
        }
    }


}



